import { getUserPhotoAPI, getUserProfileAPI, loginAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: {} // 用户基本资料对象
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  REMOVE_TOKEN: (state) => {
    state.token = ''
    removeToken()
  },
  /** ******* 操作用户信息 ********/
  SET_USER: (state, value) => {
    state.userInfo = value
  },
  REMOVE_USER: (state) => {
    state.userInfo = {}
  }

}

const actions = {
  // user login
  async loginActions(context, userInfo) {
    const res = await loginAPI(userInfo)
    context.commit('SET_TOKEN', res.data)
    return res
  },

  // user profile
  async getUserInfoActions(context) {
    const userObj = await getUserProfileAPI()
    const photoObj = await getUserPhotoAPI(userObj.data.userId)
    context.commit('SET_USER', { ...userObj.data, ...photoObj.data })
    // 返回页面权限数组
    return userObj.data.roles.menus
  },

  // user logout
  logoutActions(context) {
    context.commit('REMOVE_TOKEN')
    context.commit('REMOVE_USER')
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

